package com.shidaimanong.demo.network;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

/**
 * 学编程，关注：十代码农
 * 抖音、快手、B站、西瓜视频、今日头条
 */
public class TcpServerDemo extends Thread {
    private ServerSocket serverSocket;

    public TcpServerDemo(int port) throws IOException {
        serverSocket = new ServerSocket(port);
        serverSocket.setSoTimeout(10000);//设置超时时间
    }

    public void run() {
        while (true) {
            try {
                System.out.println("服务就绪，监听端口：" + serverSocket.getLocalPort());
                Socket server = serverSocket.accept();//在指定端口监听客户端请求
                DataInputStream in = new DataInputStream(server.getInputStream());
                System.out.println(in.readUTF());//读取客户端发送的数据并打印
                DataOutputStream out = new DataOutputStream(server.getOutputStream());
                out.writeUTF("客官，欢迎光临本店。");//想客户端发送数据
                server.close();//关闭连接
            } catch (SocketTimeoutException s) {
                System.out.println("服务器等待超时!");
                break;
            } catch (IOException e) {
                System.out.println("服务器异常！");
                break;
            }
        }
    }

    public static void main(String[] args) throws IOException {
        int serverPort = 7777;//服务器监听端口
        TcpServerDemo serverDemo = new TcpServerDemo(serverPort);
        serverDemo.start();//启动服务器监听线程
    }
}